package com.jluzh.provider;

import com.alibaba.fastjson.JSONObject;
import com.jluzh.anotation.FastJson;

import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

/**
 * @author EvanHuang
 * @date 11/5/2018 11:31 AM
 * @since
 */
@Provider
public class FastJsonBodyWriter implements MessageBodyWriter<Object> {

    @Override
    @Produces(MediaType.APPLICATION_JSON)
    public boolean isWriteable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
        return aClass.isAnnotationPresent(FastJson.class);
    }

    @Override
    public long getSize(Object o, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
        return -1;
    }

    @Override
    public void writeTo(Object o, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> multivaluedMap, OutputStream outputStream) throws IOException, WebApplicationException {
        System.out.println("providerWriter...");
        outputStream.write(JSONObject.toJSONString(o).getBytes());
    }
}

